package taskcycle

import (
	"GoMaestro/internal/entity"
	jenkins "GoMaestro/internal/jencli"
	"GoMaestro/internal/logger"
)

// TaskState 任务状态接口
type TaskState interface {
	Handle(cycle *TaskCycle, record *entity.TaskRecord) error
}

// PackagedState 已打包状态
type PackagedState struct{}

func (s *PackagedState) Handle(cycle *TaskCycle, record *entity.TaskRecord) error {
	buildID, err := cycle.triggerJenBuild(*record)
	if err != nil {
		logger.DefaultLogger.Error(err.Error())
		return err
	}
	record.CdBuildID = buildID
	record.Status = entity.StatusDeploying
	return cycle.Dao.UpdateTask(record)
}

// PackagingState 打包中状态
type PackagingState struct{}

func (s *PackagingState) Handle(cycle *TaskCycle, record *entity.TaskRecord) error {
	status, err := jenkins.GetBuildStatus(record.CiJobName, record.CiBuildID)
	if err != nil {
		logger.DefaultLogger.Error(err.Error())
		return err
	}

	switch status {
	case entity.FAILURE, entity.ABORTED:
		record.Status = entity.StatusPackageFailed
	case entity.SUCCESS:
		record.Status = entity.StatusPackaged
	}
	return cycle.Dao.UpdateTask(record)
}

// DeployingState 部署中状态
type DeployingState struct{}

func (s *DeployingState) Handle(cycle *TaskCycle, record *entity.TaskRecord) error {
	status, err := jenkins.GetBuildStatus(record.CdJobName, record.CiBuildID)
	if err != nil {
		logger.DefaultLogger.Error(err.Error())
		return err
	}

	switch status {
	case entity.FAILURE, entity.ABORTED:
		record.Status = entity.StatusDeployFailed
	case entity.SUCCESS:
		record.Status = entity.StatusDeployed
	}
	return cycle.Dao.UpdateTask(record)
}
